package ai.application;

import java.util.ArrayList;

import ai.gui.Drawable;
import ai.gui.Gui;
import ai.moving_objects.Changeable;
import ai.spatial.Vector2D;

public class Simulation {
	private Gui gui;
	private Environment environment;
	private ArrayList<Changeable> changeables;
	
	public Simulation(Gui gui, Environment environment){
		this.gui = gui;
		this.environment = environment;
		changeables = new ArrayList<Changeable>();
	}
	
	public Vector2D adjustPosition(Vector2D position){
		double x;
		if(position.getX() > this.environment.getMaxX()){
			x = this.environment.getMaxX();
		}
		else if(position.getX() < this.environment.getMinX()){
			x = this.environment.getMinX();
		}
		else{
			x = position.getX();
		}
		
		double y;
		if(position.getY() > this.environment.getMaxY()){
			y = this.environment.getMaxY();
		}
		else if(position.getY() < this.environment.getMinY()){
			y = this.environment.getMinY();
		}
		else{
			y = position.getY();
		}
		return new Vector2D(x,y);
	}
	
	public void run() {
		
		double time = 0;
		while (time < Config.getStopTime()) {
			doSimulationStep(time);
			time += Config.getSimStepSize();
			gui.getDrawArea().updateUI();
		}
		
		
	}

	private void doSimulationStep(double time) {
		try {
			Thread.sleep(33);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		updateChangeables();
	}
	
	private void updateChangeables() {
		for (Changeable changeable : this.changeables) {
			changeable.update(environment);
		}
	}

	public void addDrawables(Drawable drawable)
	{
		this.gui.addDrawable(drawable);
	}
	
	public void addChangeables(Changeable changeable)
	{
		this.changeables.add(changeable);
	}
	
}
